#!/bin/sh

# AM INSTALL SCRIPT VERSION 3.5
set -u
APP=ymir-nightly
SITE="StrikerX3/Ymir"

# CREATE DIRECTORIES AND ADD REMOVER
[ -n "$APP" ] && mkdir -p "/opt/$APP/tmp" "/opt/$APP/icons" && cd "/opt/$APP/tmp" || exit 1
printf "#!/bin/sh\nset -e\nrm -f /usr/local/bin/$APP\nrm -R -f /opt/$APP" > ../remove
printf '\n%s' "rm -f /usr/local/share/applications/$APP-AM.desktop" >> ../remove
chmod a+x ../remove || exit 1

# DOWNLOAD AND PREPARE THE APP
version=$(curl -Ls https://api.github.com/repos/StrikerX3/Ymir/releases | sed 's/[()",{} ]/\n/g' | grep -oi "https.*download.*nightly.*avx2.*tar.*xz" | head -1)
wget "$version" || exit 1
[ -e ./*tar.xz ] && tar -xJf ./*.tar.xz && rm -f ./*.tar.xz
cd ..
mv ./tmp/ymir-sdl3 ./ymir-nightly
[ -f ./tmp/gamecontroller.txt ] && mv ./tmp/gamecontroller.txt ./gamecontroller.txt
rm -R -f ./tmp || exit 1
echo "$version" > ./version
chmod a+x ./ymir-nightly || exit 1

# LINK TO PATH
ln -s "/opt/$APP/ymir-nightly" "/usr/local/bin/ymir-nightly"

# DOWNLOAD DESKTOP FILE AND ICON FROM GITHUB
mkdir -p /opt/$APP/icons
wget -q -O /opt/$APP/icons/ymir.png https://raw.githubusercontent.com/StrikerX3/Ymir/main/apps/ymir-sdl3/res/ymir.png
wget -q -O /usr/local/share/applications/ymir-nightly-AM.desktop https://raw.githubusercontent.com/StrikerX3/Ymir/main/apps/ymir-sdl3/res/io.github.strikerx3.ymir.desktop

# FIX PATHS AND NAME IN DESKTOP FILE
sed -i 's|^Exec=.*|Exec=ymir-nightly|; s|^Icon=.*|Icon=/opt/ymir-nightly/icons/ymir|' /usr/local/share/applications/ymir-nightly-AM.desktop

# SCRIPT TO UPDATE THE PROGRAM
cat >> ./AM-updater << 'EOF'
#!/bin/sh
set -u
APP=ymir-nightly
SITE="StrikerX3/Ymir"
version0=$(cat "/opt/$APP/version")
version=$(curl -Ls https://api.github.com/repos/StrikerX3/Ymir/releases | sed 's/[()",{} ]/\n/g' | grep -oi "https.*download.*nightly.*avx2.*tar.*xz" | head -1)
[ -n "$version" ] || { echo "Error getting link"; exit 1; }
if [ "$version" != "$version0" ]; then
	mkdir "/opt/$APP/tmp" && cd "/opt/$APP/tmp" || exit 1
	notify-send "Updating $APP, please wait"
	wget "$version" -O ymir-nightly.tar.xz || exit 1
	tar -xJf ymir-nightly.tar.xz && rm -f ymir-nightly.tar.xz
	cd ..
	mv --backup=t ./tmp/ymir-sdl3 ./ymir-nightly
	[ -f ./tmp/gamecontroller.txt ] && mv ./tmp/gamecontroller.txt ./gamecontroller.txt
	chmod a+x ./ymir-nightly || exit 1
	echo "$version" > ./version
	rm -R -f ./tmp ./*~
	notify-send "$APP updated!"
else
	echo "Update not needed!"
fi
EOF
chmod a+x ./AM-updater || exit 1